package com.hbt.myplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.hbt.myplus.model.Img;
import com.hbt.myplus.service.impl.ImgServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.hbt.myplus.service.IServicesService;
import com.hbt.myplus.service.impl.ServicesServiceImpl;
import com.hbt.myplus.model.Services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hbt.myplus.utils.ResponseWeb;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
    *  前端控制器
    * </p>
 *
 * @author astupidcoder
 * @since 2020-12-22
 * @version v1.0
 */
@RestController
@RequestMapping("services")


public class ServicesController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ServicesServiceImpl servicesService;

    @Autowired
    private ImgServiceImpl imgService;

    /**
     * 查询分页数据
     */
    @GetMapping(value = "/s")
    public ResponseWeb<Page> findListByPage(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,@RequestParam(name = "pageSize", defaultValue = "20") int pageSize){
        IPage<Services> servicesIPage = servicesService.getBaseMapper().selectPage(new Page<>(pageNum, pageSize), new QueryWrapper<Services>().eq("delete_flag", new Integer(0)));
        //对service进行imgs的获取
        if (servicesIPage.getRecords() != null && servicesIPage.getRecords().size() > 0){
            List<Img> imgs = imgService.listByInsIds(servicesIPage.getRecords().stream().map(a -> a.getId()).collect(Collectors.toList()));
            for (Services item:servicesIPage.getRecords()) {
                List<Img> imgs_filter = imgs.stream()
                        .filter(a -> a.getInsId().equals(item.getId()) && a.getField().equals(Services.DESC_IMG))
                        .collect(Collectors.toList());
                String[] url_list = new String[imgs_filter.size()];
                for (int i = 0; i < imgs_filter.size(); i++) {
                    url_list[i] = imgs_filter.get(i).getUrl();
                }
                item.setUrlList(url_list);
            }
        }



        Page<Services> page = new Page<>();
        page.setRecords(servicesIPage.getRecords());
        page.setTotal(servicesIPage.getTotal());
        page.setSize(pageSize);
        page.setPages(servicesIPage.getPages());
        page.setCurrent(pageNum);
        return new ResponseWeb<>(page);
    }


    /**
     * 根据id查询
     */
    @GetMapping(value = "/{id}")
    public ResponseWeb<Services> getById(@PathVariable("id") String id){
        Services service = servicesService.getById(id);
        if (service != null){
            List<Img> imgList = imgService.list(new QueryWrapper<Img>().eq("ins_id", service.getId()).eq("tbname", "services").eq("field", Services.DESC_IMG));
            if (imgList != null){
                List<Map> maps = imgList.stream().map(a -> {
                    Map map = new HashMap<String, String>();
                    map.put("name", "图片");
                    map.put("url", a.getUrl());
                    map.put("id", a.getId().toString());
                    return map;
                }).collect(Collectors.toList());
                service.setImgs(maps.toArray(new HashMap[maps.size()]));
            }else service.setImgs(new HashMap[0]);
        }
        return new ResponseWeb(service);
    }

    /**
     * 新增
     */
    @PostMapping
    public ResponseWeb<Integer> add(@RequestBody Services services){
        System.out.println(services.toString());
        boolean save = servicesService.save(services);
        Map[] imgs = services.getImgs();
        List<Img> imgList = new ArrayList<>();
        for(Map img: imgs){
            Img img_item = new Img();
            img_item.setField(Services.DESC_IMG);
            img_item.setTbname("services");
            img_item.setInsId(services.getId());
            img_item.setUrl(img.get("url").toString());
            imgList.add(img_item);
        }
        imgService.saveBatch(imgList);

        return new ResponseWeb(save);
    }



    /**
     * 删除
     */
    @DeleteMapping
    public ResponseWeb<Integer> delete(@RequestBody Map<String, List<Integer>> data){
//        System.out.println(data.get("ids").toString());
        return new ResponseWeb(servicesService.removeByIds(data.get("ids")));
//        return null;
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseWeb<Services> update(@RequestBody Services services){
        if (services == null || services.getId() == 0){
            return ResponseWeb.fail("参数错误, services is null or id is 0");
        }

        Services ser = servicesService.getById(services.getId());
        ser.setServicename(services.getServicename());
        ser.setPrice(services.getPrice());
        ser.setSno(services.getSno());
        ser.setMemo(services.getMemo());
        servicesService.updateById(ser);
        return new ResponseWeb("更新成功");
     }

}
